export class FM {
  private elList: Element[] | HTMLCollection = []
  private elRectMap: Map<Element, DOMRect> = new Map()
  public setElList (elList: Element[] | HTMLCollection) {
    this.elList = elList
    this.elRectMap.clear()
  }

  public animateReady () {
    this.elRectMap.clear()
    const len = this.elList.length
    for (let i = 0; i < len; i++) {
      const el = this.elList[i]
      this.elRectMap.set(el, el.getBoundingClientRect())
    }
  }

  public animateGo () {
    const len = this.elList.length
    const _goElRectMap = new Map<Element, DOMRect>()
    for (let i = 0; i < len; i++) {
      const el = this.elList[i]
      _goElRectMap.set(el, el.getBoundingClientRect())
    }
    for (let i = 0; i < len; i++) {
      const el = this.elList[i]
      const r1 = this.elRectMap.get(el)
      const r2 = _goElRectMap.get(el)
      if (r1 && r2) {
        el.animate([
          { transform: `translateY(${r1.y - r2.y}px) translateX(${r1.x - r2.x}px)` },
          { transform: 'translateY(0) translateX(0)' }
        ], {
          duration: 200
        })
      }
    }
    this.elRectMap = _goElRectMap
  }
}
